﻿/// <reference path="iuPlace.js" />
/// <reference path="Api/ApiReference.js" />
/// <reference path="Facebook.js" />
/// <reference path="jquery.googlemaps.pack.1.01.js" />
/// <reference path="iuPlace.Map.js" />

iuPlace.Application = {
    Types: {
      
    }
};

(function () {
    var obj = this;
    document.addEventListener("deviceready", onDeviceReady, false); 
    $(onDocumentLoaded);

    //methods
    function initialized() {
        Facebook.Initialize();
        $(iuPlace.Application).trigger("OnInitialized");
    };

    function openSession(login) { 
        Facebook.GetSession(function () {
            if (Facebook.Session) {
                validateUser();
            } else {
                if(login) {
                    Facebook.Login(Facebook.Types.DisplayType.Touch);
                } else {
                    $(iuPlace.Application).trigger("OnOpenSession", false);
                }
            }
        });
    };

    function closeSession() { 
    };

    function validateUser() {
        iuPlace.Api.Session.User = $.extend({}, iuPlace.Api.Types.User, {});    
        iuPlace.Api.Session.User.UId = Facebook.Session.UId;
        iuPlace.Api.Session.User.Name = Facebook.Session.Name;
        iuPlace.Api.Session.User.UserName = Facebook.Session.UserName;
        iuPlace.Api.Session.User.Gender = Facebook.Session.Gender == "male" ? iuPlace.Api.Types.Gender.Male : iuPlace.Api.Types.Gender.Female;
        iuPlace.Api.Session.User.DateBirthDay = Facebook.Session.DateBirthDay;
        iuPlace.Api.Session.User.ProfileUrl = Facebook.Session.ProfileUrl;
        iuPlace.Api.Session.User.AccessToken = Facebook.Session.AccessToken;
        iuPlace.Api.Session.User.TokenSecret = Facebook.Session.TokenSecret;

        iuPlace.Api.User.Login(function (dataResult) {
            if (!dataResult.IsError) {
                $(iuPlace.Application).trigger("OnOpenSession", true);
            }            
        });
    };

    //methods events
    function onDeviceReady() {  
        iuPlace.Api.Session.Container.Platform = device.platform;     
        initialized();
    };

    function onDocumentLoaded() {
        if (iuPlace.Api.Session.Container.Type == iuPlace.Api.Types.TypeContainer.Browser)            
            initialized();
    };

    //delegate events
    function onInitialized(method) {        
        $(iuPlace.Application).bind("OnInitialized", method);
    };

    function onOpenSession(method) {
        $(iuPlace.Application).bind("OnOpenSession", method);
    };

    function onCloseSession(method) {
        $(iuPlace.Application).bind("OnCloseSession", method);
    };
     
    $.extend(iuPlace.Application, {
        OpenSession: openSession,
        CloseSession: closeSession,

        OnInitialized: onInitialized,
        OnOpenSession: onOpenSession,
        OnCloseSession: onCloseSession
    });
})();